<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <ShipmentSearchForm
      v-show="showSearch"
      :query-params="queryParams"
      :sender-list="senderList"
      :receiver-list="receiverList"
      @search="handleQuery"
      @reset="resetQuery"
    />

    <!-- 工具栏 -->
    <ShipmentToolbar
      :single="single"
      :multiple="multiple"
      :show-search.sync="showSearch"
      @add="handleAdd"
      @update="handleUpdate"
      @delete="handleDelete"
      @export="handleExport"
      @refresh="getList"
    />

    <!-- 数据表格 -->
    <ShipmentTable
      :loading="loading"
      :shipment-list="shipmentList"
      @selection-change="handleSelectionChange"
      @detail="handleDetail"
    />

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改抽屉 -->
    <ShipmentFormDrawer
      :visible.sync="open"
      :title="title"
      :form="form"
      :rules="rules"
      :sender-list="senderList"
      :receiver-list="receiverList"
      @submit="submitForm"
      @cancel="cancel"
    />

    <!-- 详情抽屉 -->
    <ShipmentDetailDrawer
      :visible.sync="detailOpen"
      :shipment-info="detailForm"
    />
  </div>
</template>

<script>
import { listShipment, getShipment, addShipment, updateShipment, delShipment, exportShipment } from '@/api/logistics/shipment'
import { listSender } from '@/api/logistics/sender'
import { listReceiver } from '@/api/logistics/receiver'
import { 
  ShipmentSearchForm, 
  ShipmentToolbar, 
  ShipmentTable, 
  ShipmentFormDrawer, 
  ShipmentDetailDrawer 
} from './components'

export default {
  name: 'Shipment',
  components: {
    ShipmentSearchForm,
    ShipmentToolbar,
    ShipmentTable,
    ShipmentFormDrawer,
    ShipmentDetailDrawer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运单表格数据
      shipmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 发货方列表
      senderList: [],
      // 收货方列表
      receiverList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shipmentCode: undefined,
        senderId: undefined,
        receiverId: undefined,
        shipmentStatus: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      // 表单参数
      form: {
        shipmentId: undefined,
        shipmentCode: undefined,
        shipmentStatus: '1', // 默认待发货
        
        // 发货信息
        senderId: undefined,
        senderName: undefined,
        senderContactName: undefined,
        senderContactPhone: undefined,
        senderProvince: undefined,
        senderCity: undefined,
        senderDistrict: undefined,
        senderAddress: undefined,
        senderLongitude: undefined,
        senderLatitude: undefined,
        
        // 收货信息
        receiverId: undefined,
        receiverName: undefined,
        receiverContactName: undefined,
        receiverContactPhone: undefined,
        receiverProvince: undefined,
        receiverCity: undefined,
        receiverDistrict: undefined,
        receiverAddress: undefined,
        receiverLongitude: undefined,
        receiverLatitude: undefined,
        
        // 运输信息
        goodsName: undefined,
        goodsType: undefined,
        goodsWeight: undefined,
        goodsVolume: undefined,
        transportMode: undefined,
        estimatedShipDate: undefined,
        estimatedArrivalDate: undefined,
        freight: undefined,
        paymentMethod: undefined,
        
        // 可追溯字段
        remark: undefined
      },
      // 详情表单
      detailForm: {},
      // 表单校验
      rules: {
        shipmentCode: [
          { required: true, message: '运单编号不能为空', trigger: 'blur' }
        ],
        senderId: [
          { required: true, message: '发货方不能为空', trigger: 'change' }
        ],
        senderContactName: [
          { required: true, message: '发货联系人不能为空', trigger: 'blur' }
        ],
        senderContactPhone: [
          { required: true, message: '发货联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        senderAddress: [
          { required: true, message: '发货地址不能为空', trigger: 'blur' }
        ],
        receiverId: [
          { required: true, message: '收货方不能为空', trigger: 'change' }
        ],
        receiverContactName: [
          { required: true, message: '收货联系人不能为空', trigger: 'blur' }
        ],
        receiverContactPhone: [
          { required: true, message: '收货联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        receiverAddress: [
          { required: true, message: '收货地址不能为空', trigger: 'blur' }
        ],
        goodsName: [
          { required: true, message: '货物名称不能为空', trigger: 'blur' }
        ],
        goodsWeight: [
          { required: true, message: '货物重量不能为空', trigger: 'blur' },
          { type: 'number', message: '货物重量必须为数字', trigger: 'blur' }
        ],
        transportMode: [
          { required: true, message: '运输方式不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getSenderList()
    this.getReceiverList()
  },
  methods: {
    /** 查询运单列表 */
    getList() {
      this.loading = true
      listShipment(this.queryParams).then(response => {
        this.shipmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询发货方列表 */
    getSenderList() {
      listSender().then(response => {
        this.senderList = response.data
      })
    },
    /** 查询收货方列表 */
    getReceiverList() {
      listReceiver().then(response => {
        this.receiverList = response.data
      })
    },
    /** 查询运单历史记录 */
    getHistoryList() {
      this.historyLoading = true
      getShipmentHistory(this.historyQueryParams).then(response => {
        this.historyList = response.rows
        this.historyTotal = response.total
        this.historyLoading = false
      })
    },
    /** 查询运单轨迹 */
    getTrackList() {
      this.trackLoading = true
      getShipmentTrack(this.trackQueryParams).then(response => {
        this.trackList = response.rows
        this.trackTotal = response.total
        this.trackLoading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        shipmentId: undefined,
        shipmentCode: undefined,
        shipmentStatus: '1', // 默认待发货
        
        // 发货信息
        senderId: undefined,
        senderName: undefined,
        senderContactName: undefined,
        senderContactPhone: undefined,
        senderProvince: undefined,
        senderCity: undefined,
        senderDistrict: undefined,
        senderAddress: undefined,
        senderLongitude: undefined,
        senderLatitude: undefined,
        
        // 收货信息
        receiverId: undefined,
        receiverName: undefined,
        receiverContactName: undefined,
        receiverContactPhone: undefined,
        receiverProvince: undefined,
        receiverCity: undefined,
        receiverDistrict: undefined,
        receiverAddress: undefined,
        receiverLongitude: undefined,
        receiverLatitude: undefined,
        
        // 运输信息
        goodsName: undefined,
        goodsType: undefined,
        goodsWeight: undefined,
        goodsVolume: undefined,
        transportMode: undefined,
        estimatedShipDate: undefined,
        estimatedArrivalDate: undefined,
        freight: undefined,
        paymentMethod: undefined,
        
        // 可追溯字段
        relatedOrderCode: undefined,
        batchCode: undefined,
        traceCode: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.shipmentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加运单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const shipmentId = row.shipmentId || this.ids[0]
      getShipment(shipmentId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改运单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.shipmentId) {
            updateShipment(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addShipment(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const shipmentIds = row.shipmentId || this.ids
      this.$modal.confirm('是否确认删除运单编号为"' + shipmentIds + '"的数据项?').then(() => {
        return delShipment(shipmentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有运单数据项?').then(() => {
        this.exportLoading = true
        return exportShipment(this.queryParams)
      }).then(response => {
        this.$download.excel(response, '运单数据')
        this.exportLoading = false
      }).catch(() => {})
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.detailForm = {}
      const shipmentId = row.shipmentId
      getShipment(shipmentId).then(response => {
        this.detailForm = response.data
        this.detailOpen = true
      })
    }
  }
}
</script>